import {Component, OnInit, ElementRef, ViewChild} from '@angular/core';
import {Router, ActivatedRoute, PRIMARY_OUTLET, NavigationEnd} from '@angular/router';
import {NzMessageService} from 'ng-zorro-antd/message';
import {AppService} from '../../app.service';
import {Global} from '../../shared/global';
import {RoutingCache} from '../../RoutesCache';
import {defalutImg} from '../promotionShare/comm';

import {HomeService} from './home.service';
import { forkJoin } from 'rxjs';
import { Observable } from 'rxjs/Rx';


import {ConfigDictService} from '../../main/config/config-dict/config-dict.service';

import 'rxjs/add/operator/filter';
import {routeArrs} from './home.comm';
import { environment } from '../../../environments/environment';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
  isTestEnv: boolean = environment.envType === 'test'; // menu background
  CacheLoadingOne = false;
  text = '配件商城';
  passwordModal: any = false;
  accountModal: any = false;
  /**
   * 头像
   */
  fileVal = '';
  /**
   * 主窗体
   */
  // @ViewChild('mainScroll') mainScroll!: ElementRef;

  /**
   * 修改密码接口参数
   */
  entityParam: any = {
    //   账号
    accountNumber: null,
    // 旧密码
    oldPwd: null,
    // 新密码
    passWord: null,
    // 确认新密码
    affirmPassWord: null,
  };

  /**
   * 账号信息
   */
  accountParam: any = {
    id: null,
    // 用户名
    userName: null,
    // 姓名
    realName: null,
    // 联系方式
    phoneNumber: null,
    // 昵称
    name: null,
    // 头像
    img: null,
    // 状态 0表示可用 1表示不可用
    state: '0',
    // 备注
    remarks: null,
    isFirst: null,
    // 排序
    sort: null,
    // 角色id
    roleId: null,
  };

  /**
   * 全局 loading
   */
  messageId: any = null;
  /**
   * 当前路由
   */
  activeRoutin: any = null;
  /**
   * 面包屑路由字典
   */
  routingArr = routeArrs;
  navData: any = [];
  userInfo: any = null;
  breadcrumbs: any = {};
  /**
   * 菜单数据源
   */
  menuData?: any = null;
  /**
   * 菜单收缩
   */
  isCollapsed = false;
  fallback = defalutImg;

  headMenus: any = [];
  activeMenu: any = null;

  currentUrl: string = '';

  constructor(
    private ConfigDictService: ConfigDictService,
    private router: Router,
    private AppService: AppService,
    private message: NzMessageService,
    public activatedRoute: ActivatedRoute,
    private HomeService: HomeService
  ) {
    this.router.events.filter(event => event instanceof NavigationEnd).subscribe((event: any) => {
      this.currentUrl = event.urlAfterRedirects || '';
      // this.breadcrumbs = [];
      //set breadcrumbs

      let root: ActivatedRoute = this.activatedRoute.root;
      this.getBreadcrumbs(root);
      for (let index = 0; index < this.routingArr.length; index++) {
        const element = this.routingArr[index];
        let obj: any = {};

        if (element.path.indexOf(this.activeRoutin) != -1) {
          obj.breadcrumb = element.breadcrumb;
          obj.path = element.path;
          this.breadcrumbs = obj;
          break;
        }
        for (let index = 0; index < element.children.length; index++) {
          const c: any = element.children[index];
          if (c.path.indexOf(this.activeRoutin) != -1) {

            obj.path = element.path;
            obj.breadcrumb = c.breadcrumb;
            obj.backPath = element.path;

            this.breadcrumbs = obj;
            break;
          }
        }
      }
      this.resetMenu();
    });
  }

  ngOnInit(): void {
    // 监听页面size变化
    // Observable.fromEvent(window, 'resize').subscribe((event: any) => {
    //   // console.log('change size', event.target.innerWidth);
    //   let winSize: number = event.target.innerWidth;
    //   if (winSize < 1480) {
    //     console.log('size < 1480');
    //   }
    // });
    // this.getDictList();
    this.activeMenu = Global.activeMenu;
    if (Global.menuList) {
      this.headMenus = Global.menuList.sys || [];
      this.userInfo = Global.menuList.user;
      this.menuData = Global.menuList.sys[0].menu;
      this.resetMenu();
    } else {
      this.menuList();
    }
  }

  /**
   * Returns array of IBreadcrumb objects that represent the breadcrumb
   *
   * @class DetailComponent
   * @method getBreadcrumbs
   * @param {ActivateRoute} route
   * @param {string} url
   * @param {IBreadcrumb[]} breadcrumbs
   */
  private getBreadcrumbs(route: ActivatedRoute) {
    const ROUTE_DATA_BREADCRUMB: string = 'breadcrumb';

    //get the child routes
    let children: ActivatedRoute[] = route.children;

    //return if there are no more children
    if (children.length === 0) {
      return;
    }

    //iterate over each children
    for (let child of children) {
      let c: any = child;
      //verify primary route
      if (c.outlet !== PRIMARY_OUTLET) {
        continue;
      }

      //verify the custom data property "breadcrumb" is specified on the route
      // if (c.snapshot.data.hasOwnProperty(ROUTE_DATA_BREADCRUMB)) {
      if (c.children.length == 0) {
        this.activeRoutin = c.snapshot.url[0].path;
      }

      // }
      this.getBreadcrumbs(c);
    }
  }

  toggleCollapsed(): void {
    this.isCollapsed = !this.isCollapsed;
  }

  /**
   * 刷新缓存
   */
  refreshCache() {
    this.CacheLoadingOne = true;
    // 并联请求
    const post1 = this.AppService.refreshCache(1)
      .pipe((data) => {
        return data;
      });
    const post2 = this.AppService.refreshCache(2)
      .pipe((data) => {
        return data;
      });
    const post3 = this.AppService.refreshCache(3)
      .pipe((data) => {
        return data;
      });
    forkJoin([post1, post2, post3])
      .subscribe((data: any) => {
        if (data[0].code != 0) {
          this.createMessage('error', '系统异常，请稍后再试！');
        }
        this.createMessage('success', '数据缓存刷新成功');
        this.CacheLoadingOne = false;
      }, err => {
        this.createMessage('error', '系统异常，请稍后再试！');
        this.CacheLoadingOne = false;
      });
  }

  toRouter(path: string) {
    // if (this.router.url.indexOf(path) === -1) {

    this.router.navigate([path]);
    // this.resetMenu();
    // }
  }

  breadcrumbsPaht(path: string) {
    const url = this.router.routerState.snapshot.url;
    if (url.includes('/aisi-recyc/assessPriceTemplateEdit')) {
      this.router.navigate(['/aisi-recyc/assessPriceTemplateList']);
    } else if (url.includes('/aisi-recyc/assessTypeManageEdit')) {
      this.router.navigate(['/aisi-recyc/assessTypeManageList']);
    } else {
      history.go(-1);
    }
  }

  /**
   * 退出登录
   */
  exit() {
    this.HomeService.exit().subscribe((res: any) => {
      this.createMessage('success', '成功退出登录');
      Global.UP = null;
      for (const key in RoutingCache.handlers) {
        RoutingCache.deleteRouteSnapshot(key);
      }
      localStorage.clear();
      this.router.navigate(['login']);
    }, err => {
    });
  }

  /**
   * 查询菜单列表
   */
  menuList() {
    this.HomeService.menuList().subscribe((res: any) => {
      if (res.code != 0) {
        this.createMessage('error', '菜单获取失败');
        return;
      }

      this.headMenus = res.data.sys || [];
      this.userInfo = res.data.user;
      this.menuData = this.filterMenus();
      this.resetMenu();
    }, err => {
    });
  }

  forEachArrs(arr: any[]) {
    arr.forEach((item: any) => {
      item.menu.forEach((menu: any) => {
        menu.children.forEach((children: any) => {
          if (this.currentUrl.search(children.path) != -1) {
            this.activeMenu = item.id;
            localStorage.setItem('activeMenu', item.id);
          }
        });
      });
    })
    
    let templateMenu: any = [];
    if (this.headMenus?.length) {
      templateMenu = this.headMenus.filter((ele: any) => {
        return ele.id == this.activeMenu;
      });
    }
    this.menuData = templateMenu[0].menu;
  }
  /**
   * 重置菜单
   */
  resetMenu() {
    if (!this.menuData) {
      return;
    }

    this.forEachArrs(this.headMenus);

    this.navData = [];
    for (let index = 0; index < this.menuData.length; index++) {
      const element = this.menuData[index];
      let arr = [];
      if (element.isHide == 1 || element.isHide == null) {
        for (let k = 0; k < element.children.length; k++) {
          const c = element.children[k];
          // let selected = this.breadcrumbs.path.split("/")[1] == c.path.split("/")[1] ? true : false;
          let selected = this.breadcrumbs.path == c.path ? true : false;
          if (c.isHide == 1 || c.isHide == null) {
            arr.push({
              name: c.name,
              path: c.path,
              selected: selected
            });
          }
        }
        let open = arr.filter(function(item: any) {
          return item.selected == true;
        }).length == 0 ? false : true;
        this.navData.push({
          name: element.name,
          icon: element.icon,
          open: open,
          children: arr,
        });
      }
    }
  }

  /**
   * head 菜单跳转
   * Head Change Menu
   * @param item
   */
  changeHeadMenu(item: any) {
    if (Global.activeMenu == item.id) {
      return;
    }

    this.activeMenu = item.id;
    Global.activeMenu = item.id || 0;
    localStorage.setItem('activeMenu', item.id);
    this.menuData = this.filterMenus();

    this.router.navigate([this.menuData[0].children[0].path]);
    this.resetMenu();
  }

  // filter menus
  filterMenus() {
    let templateMenu: any = [];
    if (this.headMenus?.length) {
      templateMenu = this.headMenus.filter((ele: any) => {
        return ele.id == Global.activeMenu;
      });
    }
    return templateMenu[0].menu || [];
  }

  /**
   * 主窗口滚动
   * @param currentY 滑动位置
   * @param targetY  滑动动画时间
   */
  ScrollTop(number: any, time: any) {
    if (!time) {
      // this.mainScroll.nativeElement.scrollTop = number;
      return number;
    }
    const spacingTime = 20; // 设置循环的间隔时间  值越小消耗性能越高
    let spacingInex = time / spacingTime; // 计算循环的次数
    let nowTop = document.body.scrollTop + document.documentElement.scrollTop; // 获取当前滚动条位置
    let everTop = (number - nowTop) / spacingInex; // 计算每次滑动的距离

    let scrollTimer = setInterval(() => {
      if (spacingInex > 0) {
        spacingInex--;
        this.ScrollTop(nowTop += everTop, null);
      } else {
        clearInterval(scrollTimer); // 清除计时器
      }
    }, spacingTime);

  }

  scrollTopZero() {
    let bdDom: any = document.getElementById('content-scoll');
    bdDom.scrollTop = 0;
  }

  /**
   * 打开角色信息模态框 初始化
   * @param id
   */
  showRoleModal(id: any = null): void {
    this.passwordModal = true;
  }

  /**
   * 模态框关闭触发
   */
  handleCancel(): void {
    this.passwordModal = false;
    this.accountModal = false;
  }

  /**
   * 修改密码
   */
  revisePwd() {
    if (this.messageId != null) {
      return;
    }
    if (!this.entityParam.oldPwd) {
      return this.createMessage('warning', '原密码不能为空');
    }

    if (!this.entityParam.passWord) {
      return this.createMessage('warning', '新密码不能为空');
    }

    if (!this.entityParam.affirmPassWord) {
      return this.createMessage('warning', '确认密码不能为空');
    }
    if (this.entityParam.affirmPassWord != this.entityParam.passWord) {
      return this.createMessage('warning', '新密码和确认密码不一致');
    }

    this.createBasicMessage();
    this.entityParam.accountNumber = this.userInfo.accountNumber;
    this.HomeService.revisePwd(this.entityParam).subscribe((res: any) => {
      this.removeBasicMessage();
      if (res.code != 0) {
        return this.createMessage('error', res.message);
      }
      this.handleCancel();
      this.createMessage('success', '修改密码成功，请重新登录');
      Global.UP = null;
      localStorage.clear();
      this.router.navigate(['login']);
    }, err => {
      this.removeBasicMessage();
      this.createMessage('error', err.message);
    });
  }

  /**
   * 账号信息
   */
  showAccountModal(id: any = null) {
    this.accountModal = true;

    this.HomeService.details(id).subscribe((res: any) => {
      if (res.code != 0) {
        this.createMessage('error', res.message);
        return;
      }
      const tabData = res.data;
      this.accountParam.id = tabData.id;
      this.accountParam.userName = tabData.userName;
      this.accountParam.realName = tabData.realName;
      this.accountParam.phoneNumber = tabData.phoneNumber;
      this.accountParam.name = tabData.name;
      this.accountParam.img = tabData.img;
      this.accountParam.roleId = tabData.roleId;
      this.accountParam.state = tabData.state + '';
      this.accountParam.isFirst = tabData.isFirst;
      this.accountParam.sort = tabData.sort;
      this.accountParam.remarks = tabData.remarks;
    }, err => {

    });
  }

  /**
   * 账号信息保存
   */
  accountSave() {
    // const json = {
    //     userName: this.accountParam.userName,
    //     phoneNumber: this.accountParam.phoneNumber,
    //     name: this.accountParam.name,
    //     img: this.accountParam.img,
    // }
    if (this.messageId != null) {
      return;
    }
    if (!this.accountParam.realName) {
      this.createMessage('warning', '请输入姓名');
      return;
    }
    this.createBasicMessage();
    this.HomeService.update(this.accountParam).subscribe((res: any) => {
      this.removeBasicMessage();
      if (res.code != 0) {
        return this.createMessage('error', res.message);
      }
      this.createMessage('success', '修改成功');
      this.handleCancel();
      this.menuList();
    }, err => {
      this.removeBasicMessage();
      this.createMessage('error', err.message);
    });
  }

  /**
   * 文件上传完成回调
   * @param files
   */
  handleFileInput(files: any) {
    let fileArr = files.target.files;
    console.log(files.target.files);
    for (let index = 0; index < fileArr.length; index++) {
      const element = fileArr[index];
      this.postFile(element, (res: any) => {
        if (res.code != 0) {
          return;
        }
        this.accountParam.img = res.data;
      });
    }
  }

  /**
   * 删除图片
   */

  deleteImg() {
    this.accountParam.img = '';
    this.fileVal = '';
  }

  /**
   * 上传文件
   * @param su 上传完成回调函数
   */
  postFile(file: any, su: any) {
    this.HomeService.postFile(file).subscribe(data => {
      if (su) {
        su(data);
      }
    }, error => {

    });
  }

  /**
   *
   */
  openMenu(e: any) {
    for (const key in this.navData) {
      const element = this.navData[key];
      element.open = false;
    }
    e.open = true;
  }

  /**
   * 获取字典列表
   */
  getDictList() {
    this.ConfigDictService.getDictList({name: '', pageNum: 1, pageSize: 99}).subscribe((res: any) => {
      Global.dictData = res.data.list;
    }, err => {
    });
  }

  /**
   * 开启loading
   */
  createBasicMessage(): void {
    this.messageId = this.message.loading('正在登录...', {nzDuration: 0}).messageId;
  }

  /**
   * 移除loading
   */
  removeBasicMessage() {
    this.message.remove(this.messageId);
    this.messageId = null;
  }

  /**
   * 全局展示操作反馈信息
   * @param type 其他提示类型 success:成功 error:失败 warning:警告
   */
  createMessage(type: any, str: any): void {
    this.message.create(type, str);
  }
}
